package com.nuanshui.heatedloan.middleware.msgcenter;

import java.lang.reflect.Method;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;

import com.nuanshui.heatedloan.middleware.msgcenter.annotation.MsgParams;
import com.nuanshui.heatedloan.middleware.msgcenter.util.MsgParamsUtil;

/**
 * spring处理 注解的入口
 * @param 
 * @author guohao
 * @date 2017年2月10日 上午11:25:53
 * @since $
 */
public class MsgParamsAnnotationProcess  implements BeanPostProcessor{

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(final Object bean, final String beanName)
			throws BeansException {
		
		Class<?> targetClass = AopUtils.getTargetClass(bean);
		ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
			@Override
			public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
				MsgParams msgParams = AnnotationUtils.getAnnotation(method, MsgParams.class);
				if (msgParams != null) {//判断此方法是否加了相应的注解				
					String key = msgParams.value();
					MethodMsgParamsEndPoint methodMsgParamsEndPoint = new MethodMsgParamsEndPoint();
					methodMsgParamsEndPoint.setBean(bean);//要执行的对象
					methodMsgParamsEndPoint.setMethod(method);//要执行的方法
					methodMsgParamsEndPoint.setBeanName(beanName);//要执行的对象的名称
					MsgParamsUtil.addEndpoint(key, methodMsgParamsEndPoint);
				}
			}
		});
		
		
		return  bean;
	}
}
